package com.stylefeng.guns.rest.common.utils.aliyunoss;

import com.stylefeng.guns.rest.common.Constant;
import com.stylefeng.guns.rest.common.utils.PropertiesUtil;
import com.stylefeng.guns.rest.common.utils.TextUtil;
import com.stylefeng.guns.rest.common.utils.UserPwdEncryption;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * 阿里云/本地文件上传,仅用作图片上传，其他功能后续扩展
 * Created by wutong on 2015/12/18 0018.
 */
public class OSSUploadUtil {

    private static final Logger logger = Logger.getLogger(OSSUploadUtil.class);
    private static final String FILE_SYSTEM = "file_system";
    private static final String LOCAL_REQ_PATH = "local_req_path";
    private static OSSUploadUtil ossUploadUtil;
    private static final String BUCKET_NAME = "bucket_name";
    private static final String ACCESS_KEY_ID = "access_key_id";
    private static final String ACCESS_KEY_SECRET = "access_key_secret";
    private static final String PREFIX = "http://";
    private static final String END_POINT = "end_point";
    private static final String LOCAL_SAVE_PATH = "local_save_path";


    private OSSUploadUtil() {

    }

    public static OSSUploadUtil getInsance() {
        if (ossUploadUtil == null) {
            ossUploadUtil = new OSSUploadUtil();

        }
        return ossUploadUtil;
    }


    /**
     * 多图上传
     *
     * @param request
     * @param key
     */
    public String uploadMultiImages(ServletRequest request, String key) {
        if (request == null || TextUtil.isEmpty(key)) {
            return "";
        }
        ArrayList<String> imagesList = null;
        String images = "";
        try {


            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            if (fileMap != null) {
                imagesList = new ArrayList<>();
                ArrayList<MultipartFile> files = new ArrayList<>();
                for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
                    if (entry.getKey().startsWith(key)) {
                        files.add(entry.getValue());
                    }

                }
                imagesList = uploadImages(files);
            }

            if (imagesList != null && imagesList.size() > 0) {
                for (String string : imagesList) {
                    images = images + string + "|";
                }

                if ((!TextUtil.isEmpty(images)) && images.endsWith("|")) {
                    images = images.substring(0, images.length() - 1);
                }

            }
        } catch (Exception e) {
            return "";
        }
        return images;
    }

    private String fileKey = "";

    /**
     * 上传MP3音频文件
     * @param request
     * @param key
     * @return
     */
    public String uploadMultiAudioFile(ServletRequest request, String key) {
        if (request == null || TextUtil.isEmpty(key)) {
            return "";
        }
        String filePath = "";
        fileKey = key;
        try {

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile(key);
            filePath = uploadSingleImage(file.getInputStream(), file.getSize());

        } catch (Exception e) {
            return "";
        }

        return filePath;
    }


    /**
     * 上传MP3音频文件
     * @param file
     * @param key
     * @return
     */
    public String uploadMultiAudioFile(MultipartFile file, String key) {
        if (file == null || TextUtil.isEmpty(key)) {
            return "";
        }
        String filePath = "";
        fileKey = key;
        try {
            /*MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile(key);*/
            filePath = uploadSingleImage(file.getInputStream(), file.getSize());
        } catch (Exception e) {
            return "";
        }
        return filePath;
    }



    /**
     * 上传多个图片
     *
     * @param paths
     * @return
     */
    public ArrayList<String> uploadImagesByPath(ArrayList<String> paths) {
        if (paths == null || paths.size() == 0) {
            return null;
        }
        ArrayList<String> resultList = new ArrayList<>();
        for (String path : paths) {
            File file = new File(path);
            if (file != null && file.exists()) {
                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(file);
                    String result = uploadSingleImage(inputStream, file.length());
                    resultList.add(result);

                } catch (FileNotFoundException e) {
                    logger.error(e.getMessage());
                    continue;
                }

            }
        }
        return resultList;

    }

    /**
     * 上传单个图片
     *
     * @param path
     * @return
     */
    public String uploadSingleImageByPath(String path) {
        File file = new File(path);
        try {
            InputStream inputStream = new FileInputStream(file);
            return uploadSingleImage(inputStream, file.length());
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
            return null;
        }

    }

    /**
     * 上传单个图片
     *
     * @param file
     * @return
     */
    public String uploadSingleImage(MultipartFile file) {
        if (file == null || file.getSize() == 0) {
            return null;
        } else {
            try {
                String path = uploadSingleImage(file.getInputStream(), file.getSize());
                return path;
            } catch (IOException e) {
                logger.error(e.getMessage());
                return null;
            }

        }

    }





    /**
     * 上传多张图片
     *
     * @param files
     * @return
     */
    public ArrayList<String> uploadImages(ArrayList<MultipartFile> files) {
        ArrayList<MultipartFile> list = filterFiles(files);
        if (list == null || list.size() == 0) {
            return null;
        }

        ArrayList<String> ossPaths = new ArrayList<>();
        for (MultipartFile file : list) {
            try {
                String path = uploadSingleImage(file.getInputStream(), file.getSize());
                if (!TextUtil.isEmpty(path)) {
                    ossPaths.add(path);
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
                continue;
            }
        }
        return ossPaths;
    }


    /**
     * 过滤出需要上传的file
     *
     * @param files
     * @return
     */
    private ArrayList<MultipartFile> filterFiles(ArrayList<MultipartFile> files) {
        if (files != null && files.size() > 0) {
            ArrayList<MultipartFile> filterFiles = new ArrayList<>();
            //循环获取file数组中得文件
            for (int i = 0; i < files.size(); i++) {
                MultipartFile file = files.get(i);
                try {
                    if (file != null && file.getBytes().length > 0) {
                        filterFiles.add(file);
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    continue;
                }
            }
            return filterFiles;
        } else {
            return null;
        }

    }

    /**
     * 上传单个文件
     *
     * @param inputStream
     * @param size
     * @return
     */
    private String uploadSingleImage(InputStream inputStream, long size) {
        /*String fileSystem = PropertiesUtil.get(FILE_SYSTEM);
        if ("oss".equals(fileSystem)) {
            //阿里云oss
            return oss(inputStream, size);

        } else {
            //本地文件系统
            return local(inputStream, size);
        }*/
        return local(inputStream, size);
    }


    /**
     * 阿里云oss
     *
     * @param inputStream
     * @param size
     * @return
     */
    private String oss(InputStream inputStream, long size) {

        /*String endPint = PropertiesUtil.get(END_POINT);
        String bucketName = PropertiesUtil.get(BUCKET_NAME);
        String accessKeyId = PropertiesUtil.get(ACCESS_KEY_ID);
        String accessKeySecret = PropertiesUtil.get(ACCESS_KEY_SECRET);


        OSSClient ossClient = new OSSClient(endPint, accessKeyId, accessKeySecret);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(size);
        String fileName = "";
        if (fileKey.equals("file")) {
            fileName = UserPwdEncryption.md5("" + size + System.currentTimeMillis() + Math.random()) + ".mp3";
        } else {
            fileName = UserPwdEncryption.md5("" + size + System.currentTimeMillis() + Math.random()) + ".jpg";
        }


        PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream, objectMetadata);
        logger.debug(result == null ? "" : result.getETag());

        return PREFIX + bucketName + "." + endPint + "/" + fileName;*/
        return "";
    }

    /**
     * 本地文件系统
     *
     * @param inputStream
     * @param size
     * @return
     */
    private String local(InputStream inputStream, long size) {
//        String localReqPath = PropertiesUtil.get(LOCAL_REQ_PATH);
//        String saveDir = PropertiesUtil.get(LOCAL_SAVE_PATH);
        String saveDir = Constant.FILE_PATH;
        File saveDirFile = new File(saveDir);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        FileOutputStream fos = null;
        try {
            String fileName = "";
            if (fileKey.equals("file")) {
                fileName = UserPwdEncryption.md5("" + size + System.currentTimeMillis() + Math.random()) + ".mp4";
            } else {
                fileName = UserPwdEncryption.md5("" + size + System.currentTimeMillis() + Math.random()) + ".jpg";
            }
            fos = new FileOutputStream(saveDir + fileName);
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                fos.write(b);
            }
//            return localReqPath + fileName;
            return fileName;
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        }


        return "";
    }

    /**
     * 上传单张视频背景图片（20200504新增，用于客户端上传视频背景图片）
     * @param file
     * @param key
     * @return
     */
    public String uploadSgleImageFileBg(MultipartFile file, String key) {
        if (file == null || TextUtil.isEmpty(key)) {
            return "";
        }
        String filePath = "";
        fileKey = key;
        try {
            filePath = localVedioBg(file.getInputStream(), file.getSize());
        } catch (Exception e) {
            return "";
        }
        return filePath;
    }

    /**
     * 本地文件系统
     *
     * @param inputStream
     * @param size
     * @return
     */
    private String localVedioBg(InputStream inputStream, long size) {
        Date date = new Date();
        String saveDir = Constant.FILE_VEDIO_BG_PATH;
        String path=saveDir+new SimpleDateFormat("yyyy-MM-dd").format(date)+"/";
        File saveDirFile = new File(path);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        FileOutputStream fos = null;
        String fileName = "";
        try {
            fileName = UserPwdEncryption.md5("" + size + System.currentTimeMillis() + Math.random()) + ".jpg";
            fos = new FileOutputStream(path + fileName);
            byte[] b = new byte[1024];
            while ((inputStream.read(b)) != -1) {
                fos.write(b);
            }
            return fileName;
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }
            }

        }
        return "";
    }
}
